import { AxiosRequestConfig } from 'axios'
import instance from './axios'
import api from '../api'

export const $http = async (path: string, params = {}, options = {}) => {
  const { method, url } = api[path as keyof typeof api]
  const requestItem: AxiosRequestConfig<any> = {
    method: method === 'resetful' ? 'get' : method,
    url: method === 'resetful' ? toRest(url, params) : url,
    [getRequestParamsKey(method)]: params,
    ...options
  }
  try {
    const res = await instance(requestItem)
    return res
  } catch (error) {
    return error
  }
}

function getRequestParamsKey(method: string) {
  return method === 'get' ? 'params' : 'data'
}

//restful路径参数替换
function toRest (url, params) {
  let paramArr = url.match(/(?<=\{).*?(?=\})/gi)
  paramArr.forEach(el => {
    url = url.replace(`{${el}}`, params[el])
  })
  return url
}


